// Written by Dale J Williams.
// Licensed under MPL 1.1 unless otherwise specified. 
// http://www.mozilla.org/MPL/MPL-1.1.html

package engineDJW {
	
	import engineDJW.entities.Entity;
	import engineDJW.GameCore;
	import engineDJW.interfaces.IBounds;
	import engineDJW.map.GameMap;
	import engineDJW.map.MapPiece;
	import engineDJW.screens.GameScreen;
	import flash.display.Graphics;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author Dale J Williams
	 */
	public class GameEngine extends GameScreen {
		
		static private var _instance	:GameEngine;
		
		protected var _map		:GameMap;
		protected var _camera	:Point;
		protected var _screen	:Rectangle;
		
		protected var _player	:Entity;
		
		protected var _toX		:Number;
		protected var _toY		:Number;
		
		private var _collisions	:Vector.<MapPiece>;
		
		public function GameEngine($map:GameMap, $player:Entity) {
			_map = $map;
			_player = $player;
			super("engine");
			init();
		}
		
		private function init():void {
			if (_instance) throw new Error("Engine instance exists.");
			_instance = this;

			_camera = new Point();
			_screen = new Rectangle();
			_collisions = new Vector.<MapPiece>();			
			addChild(_map);
			
			var g:Graphics = graphics;
			g.beginFill(0);
			g.drawRect(0, 0, _width, _height);
			g.endFill();
			
			opaqueBackground = 0x000000;
		}
		
		override public function animIn():void {
			super.animIn();
			reset();
			_map.addEntity(_player);
			start();			
		}
		
		public function start():void {
			addEventListener(Event.ENTER_FRAME, update);	
		}
		
		public function stop():void {
			removeEventListener(Event.ENTER_FRAME, update);
		}
			
		protected function reset():void {
			
		}
		
		override public function animOut():void {
			stop();
			animOutComplete();
		}
		
		protected function update(e:Event = null):void {
			_map.update();
		}
		
		private function withinScreen(boundObject:IBounds):Boolean {
			return boundObject.bounds.right > _screen.left && boundObject.bounds.left < _screen.right && boundObject.bounds.bottom > _screen.top && boundObject.bounds.top < _screen.bottom;
		} 
		
		private function getAsset($name:String):MovieClip {
			return GameCore.instance.loader.getContent($name) as MovieClip;
		}
		
		public function get player():Entity { return _player; }	
		
		static public function get instance():GameEngine { return _instance; }
		
	}

}